package cn.appsys.controller.front;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.appsys.constant.Constant;
import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.pojo.Page;
import cn.appsys.service.front.appcategory.FrontAppcategoryService;
import cn.appsys.service.front.appinfo.FrontAppinfoService;
import cn.appsys.service.front.appversion.FrontAppversionService;
import cn.appsys.service.front.datadictionary.FrontDictionaryService;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

/**
 * 处理app维护页处理器
 * 
 * @author administrader
 * 
 */
@Controller
@RequestMapping("/front/app")
public class FrontAppController {

	@Resource
	private FrontAppinfoService frontAppinfoService; // appinfo逻辑接口

	@Resource
	private FrontDictionaryService frontDictionaryService; // 字典数据逻辑接口

	@Resource
	private FrontAppcategoryService frontAppcategoryService; // appcategory逻辑接口

	@Resource
	private FrontAppversionService frontAppversionService; // 版本逻辑接口

	/**
	 * 分页查询数据信息并跳转到app维护页面
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public String toAppinfolist(
			Model model,
			@RequestParam(value = "querySoftwareName", required = false) String querySoftwareName,
			@RequestParam(value = "queryStatus", required = false) Integer queryStatus,
			@RequestParam(value = "queryFlatformId", required = false) Integer queryFlatformId,
			@RequestParam(value = "queryCategoryLevel1", required = false, defaultValue = "0") Integer queryCategoryLevel1,
			@RequestParam(value = "queryCategoryLevel2", required = false, defaultValue = "0") Integer queryCategoryLevel2,
			@RequestParam(value = "queryCategoryLevel3", required = false, defaultValue = "0") Integer queryCategoryLevel3,
			@RequestParam(value = "currPageNo", required = false, defaultValue = "1") Integer currPageNo) {

		// 得到总记录数
		int totalCount = frontAppinfoService.queryCount(querySoftwareName,
				queryStatus, queryFlatformId, queryCategoryLevel1,
				queryCategoryLevel2, queryCategoryLevel3);
		// 封装page对象
		Page page = new Page();
		page.setPageSize(5); // 每页显示五条
		page.setCurrPageNo(currPageNo); // 当前页码
		page.setTotalCount(totalCount); // 总的记录数
		Integer from = (page.getCurrPageNo() - 1) * page.getPageSize(); // 起始位置偏移量

		// 查询根据参数查询出appinfo数据
		List<AppInfo> appInfoList = frontAppinfoService.queryAppPageInfo(
				querySoftwareName, queryStatus, queryFlatformId,
				queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3,
				from, page.getPageSize());

		// 查询出状态信息
		List<DataDictionary> statusList = frontDictionaryService
				.findDataDictionaries("APP_STATUS");
		// 查询出所属平台信息
		List<DataDictionary> flatFormList = frontDictionaryService
				.findDataDictionaries("APP_FLATFORM");
		// 一级分类
		List<AppCategory> categoryLevel1List = frontAppcategoryService
				.queryById(null);

		List<AppCategory> categoryLevel2List = null; // 二级分类列表
		List<AppCategory> categoryLevel3List = null; // 三级分类列表
		if (queryCategoryLevel2 != null && queryCategoryLevel2 != 0) {
			// 查询二级分类信息
			categoryLevel2List = frontAppcategoryService
					.queryById(queryCategoryLevel2);
			model.addAttribute("categoryLevel2List", categoryLevel2List);
		}
		if (queryCategoryLevel3 != null && queryCategoryLevel3 != 0) {
			// 查询三级分类信息
			categoryLevel3List = frontAppcategoryService
					.queryById(queryCategoryLevel3);
			model.addAttribute("categoryLevel3List", categoryLevel3List);
		}

		// 将查询的数据进行反显
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryStatus", queryStatus);
		model.addAttribute("queryFlatformId", queryFlatformId);
		model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);

		// 保存到model作用域中 在jsp页面中显示
		model.addAttribute("statusList", statusList); // 查询出状态信息
		model.addAttribute("flatFormList", flatFormList);// 查询出所属平台信息
		model.addAttribute("categoryLevel1List", categoryLevel1List);// 一级分类
		model.addAttribute("categoryLevel2List", categoryLevel2List);// 二级分类
		model.addAttribute("categoryLevel3List", categoryLevel3List);// 三级分类
		model.addAttribute("appInfoList", appInfoList); // 查询出appinfo数据
		model.addAttribute("pages", page); // 分页
		return "developer/appinfolist";

	}

	/**
	 * 异步实现三级联动
	 * 
	 * @param pid
	 * @return
	 */
	@RequestMapping("/queryCategoryListByParentId")
	@ResponseBody
	public Object queryCategoryListByParentId(@RequestParam("pid") Integer pid) {
		List<AppCategory> appCategryList = frontAppcategoryService
				.queryById(pid);
		return appCategryList;
	}

	/**
	 * 跳转到新增appinfo信息界面去
	 * 
	 * @return
	 */
	@RequestMapping("/appinfAdd")
	public String toAddinfo() {
		return "developer/appinfoadd";
	}

	/**
	 * 异步显示所属平台所有信息
	 * 
	 * @param typeCode
	 * @return
	 */
	@RequestMapping("/datadictionarylist.json")
	@ResponseBody
	public Object datadictionarylist(@RequestParam("tcode") String typeCode) {
		List<DataDictionary> flatFormList = frontDictionaryService
				.findDataDictionaries(typeCode);
		return flatFormList;
	}

	/**
	 * 异步验证Apk名称是否存在
	 * 
	 * @param APKName
	 * @return
	 */
	@RequestMapping("/apkexist.json")
	@ResponseBody
	public String apkexist(@RequestParam("APKName") String APKName) {
		Map<String, String> map = new HashMap<String, String>();
		AppInfo appInfo = frontAppinfoService.queryAppInfoNameAndApk(null,
				APKName);
		if (StringUtils.isNullOrEmpty(APKName)) {
			map.put("APKName", "empty");
		} else if (appInfo != null) {
			map.put("APKName", "exist");
		} else {
			map.put("APKName", "noexist");
		}
		return JSONArray.toJSONString(map);
	}

	/**
	 * 异步验证App名称是否存在名称是否存在
	 * 
	 * @param APKName
	 * @return
	 */
	@RequestMapping("/softwareNamEexist.json")
	@ResponseBody
	public String softwareNamEexist(
			@RequestParam("softwareName") String softwareName) {
		Map<String, String> map = new HashMap<String, String>();
		AppInfo appInfo = frontAppinfoService.queryAppInfoNameAndApk(
				softwareName, null);
		if (StringUtils.isNullOrEmpty(softwareName)) {
			map.put("SoftwareName", "empty");
		} else if (appInfo != null) {
			map.put("SoftwareName", "exist");
		} else {
			map.put("SoftwareName", "noexist");
		}
		return JSONArray.toJSONString(map);
	}

	/**
	 * 进行新增appinfo操作
	 * 
	 * @return
	 */
	@RequestMapping("/appinfoaddsave")
	public String appinfoaddsave(AppInfo appInfo,
			@RequestParam("a_logoPicPath") MultipartFile attach,
			HttpSession session, HttpServletRequest request) {
		String logoPicPath = null; // 上传图片的相对路径
		String logoLocPath = null; // 上传图片的绝对路劲
		if (!attach.isEmpty()) { // 如果attach不等于空
			// 获取到当前项目的Tomcat部署的绝对路径 path是保存上传文件的路径
			// File.separator 得到的是两个//
			String path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attach.getOriginalFilename(); // 得到上传文件的名字
			String prefix = FilenameUtils.getExtension(oldFileName); // 得到上传文件名字的后缀
			if (attach.getSize() > 500000) { // 上传文件大小不能大于500kb
				request.setAttribute("fileUploadError", "文件大小不能超过500KB");
				return "redirect:/front/app/appinfAdd";
			} else if (prefix.equalsIgnoreCase("jpg")
					|| prefix.equalsIgnoreCase("jpeg")
					|| prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("pneg")) { // 判断上传文件是否正确的后缀
				// 重新构建一个新的文件名字(避免上传文件名重复)
				String newfileName = appInfo.getAPKName() + ".jpg";
				// 通过path文件的保存路径，以及新的文件名创建一个file对象
				File file = new File(path, newfileName);
				if (!file.exists()) { // 判断当前文件名是否存在 如果不存在则创建这个文件所在的目录
					file.mkdirs();
				}
				try {
					// 实现最终文件上传
					attach.transferTo(file);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
					request.setAttribute("fileUploadError", "文件上传失败！");
					return "redirect:/front/app/appinfAdd";
				}
				// 设置文件的上传路径
				// 格式为： 项目名/statics/uploadfiles/上传的图片
				logoPicPath = request.getContextPath() + File.separator
						+ "statics" + File.separator + "uploadfiles"
						+ File.separator + newfileName;
				logoLocPath = path + File.separator + newfileName; // 保存的是图片的绝对路径
			} else {
				request.setAttribute("fileUploadError",
						"上传文件不满足JPG,JPEG,PNG,PNEG格式");
				return "redirect:/front/app/appinfAdd";
			}
		}

		// 执行新增操作
		DevUser devUser = (DevUser) session
				.getAttribute(Constant.DEV_USER_SESSION); // 获取到当前登入者信息
		appInfo.setCreatedBy(devUser.getId()); // 创建者为当前登入者id
		appInfo.setCreationDate(new Date()); // 创建时间为当前时间
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setLogoPicPath(logoPicPath);
		int relust = frontAppinfoService.addAppInfo(appInfo); // 新增方法
		if (relust > 0) {
			return "redirect:/front/app/list";
		} else {
			return "redirect:/front/app/appinfAdd";
		}
	}

	/**
	 * 跳转到新增版本号页面jsp
	 * 
	 * @return
	 */
	@RequestMapping("/appversionadd/{id}")
	public String appversionadd(@PathVariable Integer id, Model model) {
		List<AppVersion> appVersionList = frontAppversionService
				.queryAppVersions(id);
		AppVersion appVersion = new AppVersion();
		appVersion.setAppId(id);
		model.addAttribute("appVersion", appVersion);
		model.addAttribute("appVersionList", appVersionList);
		return "developer/appversionadd";
	}

	/**
	 * 新增版本
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addversionsave", method = RequestMethod.POST)
	public String addversionsave(
			AppVersion appVersion,
			@RequestParam(value = "a_downloadLink", required = false) MultipartFile attach,
			HttpServletRequest request, HttpSession session,
			@RequestParam(value = "appId", required = false) Integer appId) {
		String downloadLink = null; // 相对路径
		String apkLocPath = null; // 绝对路径
		String apkFileName = null; // 文件名
		if (!attach.isEmpty()) { // 如果attach不等于空
			// 获取到当前项目的Tomcat部署的绝对路径 path是保存上传文件的路径
			// File.separator 得到的是两个//
			String path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attach.getOriginalFilename(); // 得到上传文件的名字
			String prefix = FilenameUtils.getExtension(oldFileName); // 得到上传文件名字的后缀
			if (attach.getSize() > 5000000) { // 上传文件大小不能大于500kb
				session.setAttribute("Error", "文件大小不能超过500KB");
				return "redirect:/front/app/appversionadd/"
						+ appVersion.getAppId();
			} else if (prefix.equalsIgnoreCase("apk")) { // 判断上传文件是否正确的后缀
				// 重新构建一个新的文件名字(避免上传文件名重复)
				AppInfo appInfo = frontAppinfoService
						.queryInfoByIdAndAPK(appVersion.getAppId());
				apkFileName = appInfo.getAPKName() + appVersion.getVersionNo()
						+ ".apk";
				// 通过path文件的保存路径，以及新的文件名创建一个file对象
				File file = new File(path, apkFileName);
				if (!file.exists()) { // 判断当前文件名是否存在 如果不存在则创建这个文件所在的目录
					file.mkdirs();
				}
				try {
					// 实现最终文件上传
					attach.transferTo(file);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
					session.setAttribute("Error", "文件上传失败！");
					return "redirect:/front/app/appversionadd/"
							+ appVersion.getAppId();
				}
				// 设置文件的上传路径
				// 格式为： 项目名/statics/uploadfiles/上传的图片
				downloadLink = request.getContextPath() + File.separator
						+ "statics" + File.separator + "uploadfiles"
						+ File.separator + apkFileName;
				apkLocPath = path + File.separator + apkFileName; // 保存的是图片的绝对路径
			} else {
				session.setAttribute("Error", "上传文件不满足apk,请重新上传");
				return "redirect:/front/app/appversionadd/"
						+ appVersion.getAppId();
			}
		}
		DevUser user = (DevUser) session
				.getAttribute(Constant.DEV_USER_SESSION); // 获取当前管理员用户信息
		appVersion.setCreatedBy(user.getId());
		appVersion.setCreationDate(new Date());
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setApkFileName(apkFileName);
		appVersion.setDownloadLink(downloadLink);
		int reluse = frontAppversionService.addAppVersions(appVersion);
		if (reluse > 0) {
			AppInfo info = new AppInfo();
			info.setId(appVersion.getAppId());
			info.setVersionId(appVersion.getId());
			frontAppinfoService.updateAppinfo(info);
			return "redirect:/front/app/list";
		}

		return "redirect:/front/app/appversionadd/" + appVersion.getAppId();
	}

	/**
	 * 跳转到修改appinfo页面并进行信息查询显示到页面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/infomodify/{id}")
	public String infomodify(@PathVariable Integer id, Model model) {
		AppInfo appInfo = frontAppinfoService.queryInfoByIdAndAPK(id); // 根据id查询应用信息
		model.addAttribute("appInfo", appInfo);
		return "developer/appinfomodify";
	}

	/**
	 * 修改页面异步删除图片
	 * 
	 * @return
	 */
	@RequestMapping(value = "/delfile.json", method = RequestMethod.GET)
	@ResponseBody
	public Object delfile(
			@RequestParam(value = "id", required = false) Integer id) {
		Map<String, String> map = new HashMap<String, String>();
		AppInfo appInfo = frontAppinfoService.queryInfoByIdAndAPK(id);
		File file = new File(appInfo.getLogoLocPath());
		if (file.exists()) {
			if (file.delete()) {
				if (frontAppinfoService.updateLogoPathById(id) > 0) {
					map.put("result", "success");
				}
			}
		} else {
			frontAppinfoService.updateLogoPathById(id);
			map.put("result", "failed");
		}
		return map;
	}

	/**
	 * 执行修改appinfo新增操作
	 */
	@RequestMapping(value = "/appinfomodifysave")
	public String appinfomodifysave(
			AppInfo appInfo,
			HttpServletRequest request,
			HttpSession session,
			@RequestParam(value = "attach", required = false) MultipartFile attach) {
		String logoPicPath = null; // 上传图片的相对路径
		String logoLocPath = null; // 上传图片的绝对路劲
		if (!attach.isEmpty()) { // 如果attach不等于空
			// 获取到当前项目的Tomcat部署的绝对路径 path是保存上传文件的路径
			// File.separator 得到的是两个//
			String path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attach.getOriginalFilename(); // 得到上传文件的名字
			String prefix = FilenameUtils.getExtension(oldFileName); // 得到上传文件名字的后缀
			if (attach.getSize() > 500000) { // 上传文件大小不能大于500kb
				request.setAttribute("fileUploadError", "文件大小不能超过500KB");
				return "redirect:/front/app/appinfAdd";
			} else if (prefix.equalsIgnoreCase("jpg")
					|| prefix.equalsIgnoreCase("jpeg")
					|| prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("pneg")) { // 判断上传文件是否正确的后缀
				// 重新构建一个新的文件名字(避免上传文件名重复)
				String newfileName = appInfo.getAPKName() + ".jpg";
				// 通过path文件的保存路径，以及新的文件名创建一个file对象
				File file = new File(path, newfileName);
				if (!file.exists()) { // 判断当前文件名是否存在 如果不存在则创建这个文件所在的目录
					file.mkdirs();
				}
				try {
					// 实现最终文件上传
					attach.transferTo(file);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
					request.setAttribute("fileUploadError", "文件上传失败！");
					return "redirect:/front/app/appinfAdd";
				}
				// 设置文件的上传路径
				// 格式为： 项目名/statics/uploadfiles/上传的图片
				logoPicPath = request.getContextPath() + File.separator
						+ "statics" + File.separator + "uploadfiles"
						+ File.separator + newfileName;
				logoLocPath = path + File.separator + newfileName; // 保存的是图片的绝对路径
			} else {
				request.setAttribute("fileUploadError",
						"上传文件不满足JPG,JPEG,PNG,PNEG格式");
				return "redirect:/front/app/appinfAdd";
			}
		}
		DevUser user = (DevUser) session
				.getAttribute(Constant.DEV_USER_SESSION);
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setModifyBy(user.getId());
		appInfo.setModifyDate(new Date());
		int result = frontAppinfoService.updateAppinfo(appInfo);
		if (result > 0) {
			return "redirect:/front/app/list";
		} else {
			return "developer/appinfomodify";
		}

	}

	/**
	 * 跳转到修改版本信息页面
	 * 
	 * @param versionid
	 * @param appinfoid
	 * @param session
	 * @return
	 */
	@RequestMapping("/appversionmodify/vid/{versionid}/aid/{appinfoid}")
	public String appversionmodify(@PathVariable Integer versionid,
			@PathVariable Integer appinfoid, HttpSession session) {
		AppVersion appVersion = frontAppversionService.queryAppVersionKyID(
				versionid, null);
		List<AppVersion> appVersionList = frontAppversionService
				.queryAppVersions(appinfoid);
		session.setAttribute("appVersion", appVersion);
		session.setAttribute("appVersionList", appVersionList);
		return "developer/appversionmodify";

	}

	/**
	 * 异步删除apk
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delfileapk.json", method = RequestMethod.GET)
	@ResponseBody
	public Object delfileapk(
			@RequestParam(value = "id", required = false) Integer id) {
		Map<String, String> map = new HashMap<String, String>();
		AppVersion appVersion = frontAppversionService.queryAppVersionKyID(id,
				null);
		File file = new File(appVersion.getApkLocPath());
		if (file.exists()) {
			if (file.delete()) {
				if (frontAppversionService.updateAppVersionApk(id) > 0) {
					map.put("result", "success");
				}
			}
		} else {
			frontAppversionService.updateAppVersionApk(id);
			map.put("result", "failed");
		}
		return map;
	}

	/**
	 * 进行修改版本信息操作
	 * 
	 * @param appVersion
	 * @param attach
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/appversionmodifysave")
	public String appversionmodifysave(
			AppVersion appVersion,
			@RequestParam(value = "attach", required = false) MultipartFile attach,
			HttpServletRequest request, HttpSession session) {
		String downloadLink = null; // 相对路径
		String apkLocPath = null; // 绝对路径
		String apkFileName = null; // 文件名
		if (!attach.isEmpty()) { // 如果attach不等于空
			// 获取到当前项目的Tomcat部署的绝对路径 path是保存上传文件的路径
			// File.separator 得到的是两个//
			String path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attach.getOriginalFilename(); // 得到上传文件的名字
			String prefix = FilenameUtils.getExtension(oldFileName); // 得到上传文件名字的后缀
			if (attach.getSize() > 5000000) { // 上传文件大小不能大于500kb
				session.setAttribute("fileUploadError", "文件大小不能超过500KB");
				return "redirect:/front/app/appversionmodify/vid/"
						+ appVersion.getId() + "/aid/" + appVersion.getAppId();
			} else if (prefix.equalsIgnoreCase("apk")) { // 判断上传文件是否正确的后缀
				// 重新构建一个新的文件名字(避免上传文件名重复)
				AppInfo appInfo = frontAppinfoService
						.queryInfoByIdAndAPK(appVersion.getAppId());
				apkFileName = appInfo.getAPKName() + appVersion.getVersionNo()
						+ ".apk";
				// 通过path文件的保存路径，以及新的文件名创建一个file对象
				File file = new File(path, apkFileName);
				if (!file.exists()) { // 判断当前文件名是否存在 如果不存在则创建这个文件所在的目录
					file.mkdirs();
				}
				try {
					// 实现最终文件上传
					attach.transferTo(file);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
					session.setAttribute("fileUploadError", "文件上传失败！");
					return "redirect:/front/app/appversionmodify/vid/"
							+ appVersion.getId() + "/aid/"
							+ appVersion.getAppId();
				}
				// 设置文件的上传路径
				// 格式为： 项目名/statics/uploadfiles/上传的图片
				downloadLink = request.getContextPath() + File.separator
						+ "statics" + File.separator + "uploadfiles"
						+ File.separator + apkFileName;
				apkLocPath = path + File.separator + apkFileName; // 保存的是图片的绝对路径
			} else {
				session.setAttribute("fileUploadError", "上传文件不满足apk,请重新上传");
				return "redirect:/front/app/appversionmodify/vid/"
						+ appVersion.getId() + "/aid/" + appVersion.getAppId();
			}
		}
		DevUser user = (DevUser) session
				.getAttribute(Constant.DEV_USER_SESSION); // 获取当前管理员用户信息
		appVersion.setModifyBy(user.getId()); // 修改者为当前用户id
		appVersion.setModifyDate(new Date()); // 修改时间为北京时间
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setApkFileName(apkFileName);
		appVersion.setDownloadLink(downloadLink);
		int result = frontAppversionService.updateAppVersion(appVersion);
		if (result > 0) {
			return "redirect:/front/app/list";
		}
		return "redirect:/front/app/appversionmodify/vid/" + appVersion.getId()
				+ "/aid/" + appVersion.getAppId();

	}

	/**
	 * 查看appindo应用详细
	 * 
	 * @param appinfoid
	 * @return
	 */
	@RequestMapping(value = "/appview/{appinfoid}")
	public String appview(@PathVariable Integer appinfoid, Model model) {
		AppInfo appInfo = frontAppinfoService.queryInfoByIdAndAPK(appinfoid);
		List<AppVersion> appVersionList = frontAppversionService
				.queryAppVersions(appinfoid);
		model.addAttribute("appInfo", appInfo);
		model.addAttribute("appVersionList", appVersionList);
		return "developer/appinfoview";
	}

	/**
	 * 异步删除应用信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delapp.json")
	@ResponseBody
	public Object delapp(@RequestParam("id") Integer id) {
		Map<String, String> map = new HashMap<String, String>();
		AppInfo appInfo = frontAppinfoService.queryInfoByIdAndAPK(id);
		List<AppVersion> listAppVersions = frontAppversionService
				.queryAppVersions(id);
		if (appInfo != null) { // 根据id查询出是否有数据
			try {
				File appInfofile = new File(appInfo.getLogoLocPath()); // 看是否路径下有文件
				if (appInfofile.exists()) {
					appInfofile.delete(); // 有则删除掉
				}
				frontAppinfoService.delAppinfo(id); // 执行根据id删除应用信息
				if (listAppVersions.size() > 0) { // 判断版本信息里面是否有数据
					for (AppVersion appVersion : listAppVersions) {
						File appVersionfile = new File(
								appVersion.getApkLocPath());
						if (appVersionfile.exists()) {// 有则删除掉
							appInfofile.delete();
						}
					}
					frontAppversionService.delAppVersion(id); // 删除版本信息
				}
			} catch (Exception e) {
				map.put("delResult", "false");
				e.printStackTrace();
			}
			map.put("delResult", "true");
		} else {
			map.put("delResult", "notexist"); // 表示不存在
		}
		return map;
	}

	/**
	 * 异步进行上架下架操作
	 * 
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/sale.json", method = RequestMethod.PUT,produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String sale(@RequestParam("appId") Integer appId) {
		System.err.println(appId);
		Map<String, String> map = new HashMap<String, String>();
		AppInfo appInfo = frontAppinfoService.queryInfoByIdAndAPK(appId);
		System.err.println(appInfo.getStatus());
		if (appInfo.getStatus() == 4) {  //是下架的时候
			map.put("errorCode", "0");
			appInfo.setStatus(5);
			appInfo.setId(appId);
			int result = frontAppinfoService.updateAppinfo(appInfo);
			if (result > 0) {
				map.put("resultMsg", "success");
			}
		}else if (appInfo.getStatus() == 5) {
			map.put("errorCode", "0");
			appInfo.setStatus(4);
			appInfo.setId(appId);
			int result = frontAppinfoService.updateAppinfo(appInfo);
			if (result > 0) {
				map.put("resultMsg", "success");
			}
		}else {
			map.put("resultMsg", "failed");
		}
		return JSONArray.toJSONString(map);
	}

}
